package com.example.martian.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.martian.config.util.RedisUtils;
import com.example.martian.mapper.CustodyMapper;
import com.example.martian.mapper.MartianOrePoolMapper;
import com.example.martian.mapper.RedPacketMapper;
import com.example.martian.pojo.YzcmInformation;
import com.example.martian.utils.*;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import jnr.ffi.annotations.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class MartianOrePoolService {

    @Autowired
    private MartianOrePoolMapper martianOrePoolMapper;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private Web3j web3j;

    @Autowired
    private Web3JConfig web3JConfig;

    @Autowired
    private RedPacketMapper redPacketMapper;

    @Autowired
    private CustodyMapper custodyMapper;

    @Autowired
    CustodyUtils custodyUtils;

    @Autowired
    private ExchangeRateUtils exchangeRateUtils;

    @Autowired
    private RedisUtils redisUtils;

    private static final Logger LOG = (Logger) LoggerFactory.getLogger(Web3JConfig.class);

    private static final String APIKEY = "R7R44S6RFV4EP7P9H3W9JHCF1FTTBZX1TR";

    private static final String ETHURL = "https://api-cn.etherscan.com/api?module=block&action=getblockreward&";

    @Transactional
    public Object selectMillAll(Integer goodsType) throws ParseException {
        int typeMill = 3;
        JSONArray utilsMill = custodyUtils.getMill(goodsType,typeMill);
        return Utils.toJSON("访问成功",utilsMill.toString(),"0");
    }

    //订单查询
    @Transactional
    public Object selectOrderByAddress(String address,Integer type){
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectOrderByAddress(address,type);
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("order_number",map.get("cmc_order_number"));
            jsonObject.put("payment_method",map.get("cmc_payment_method"));
            jsonObject.put("order_type",map.get("cmc_order_type"));
            jsonObject.put("number",map.get("cmc_number"));
            jsonObject.put("logo",map.get("cmc_logo"));
            jsonObject.put("payment_money",map.get("cmc_payment_money"));
            jsonObject.put("address",map.get("cmc_address"));
            jsonObject.put("product_name",map.get("cmc_product_name"));
            jsonObject.put("zt",map.get("cmc_zt"));
            jsonObject.put("create_time",map.get("cmc_create_time"));
            Integer productId = Integer.parseInt(map.get("cmc_product_id").toString());
            if (Integer.parseInt(map.get("cmc_zt").toString()) == 2){
                List<Map<String, Object>> maps = martianOrePoolMapper.selectMillAllById(productId);
                for (Map<String,Object> millMap : maps){
                    BigDecimal millCount = new BigDecimal(millMap.get("buynumber").toString()).
                            add(new BigDecimal(map.get("cmc_number").toString()));
                    martianOrePoolMapper.updateMillCount(millCount,productId);
                }
            }
            if (Integer.parseInt(map.get("cmc_zt").toString()) == 0 &&
                    Integer.parseInt(map.get("cmc_payment_method").toString()) == 2){
                boolean exists = redisUtils.exists(address + "Reward");
                if (exists){
                    List<Map<String,Object>> maps = redisUtils.getCacheListInMap(address + "Reward");
                    for (Map<String,Object> objectMap : maps){
                        String addressReward = objectMap.get("address").toString();
                        String reward = objectMap.get("reward").toString();
                        String usdtMoney = martianOrePoolMapper.selectUsdtMoneyByAddress(addressReward);//邀请人的USDT余额
                        String directDecimal = new BigDecimal(reward).add(new BigDecimal(usdtMoney)).toPlainString();
                        martianOrePoolMapper.updateUsdtBalance(directDecimal,addressReward);
                        redisUtils.clearCache(address + "Reward");
                    }
                }
            }
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //热销
    @Transactional
    public Object selectMillAllByHost() throws ParseException {
        String[] coin = new String[]{"BTC,ETH"};
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllByHost();
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                if (map.get("cmc_subarea").equals("BTC")){
                    Object btcEarningsByDay = web3JConfig.getBtcEarningsByDay("BTC");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateBtc = new BigDecimal(btcEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateBtc);
                }
                if (map.get("cmc_subarea").equals("ETH")) {
                    Object ethEarningsByDay = getEthEarningsByDay("ETH");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateEth = new BigDecimal(ethEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateEth);
                }
                jsonObject.put("image",map.get("image"));
                jsonObject.put("mill_cost",map.get("mill_cost"));
                jsonObject.put("hashrate",map.get("hashrate"));
                jsonObject.put("name",map.get("name"));
                jsonObject.put("cmc_subarea",map.get("cmc_subarea"));
                jsonObject.put("activity_price",map.get("activity_price"));
                jsonObject.put("mill_time",map.get("mining_time"));
                jsonObject.put("productId",map.get("cmc_id"));
                jsonObject.put("millCount",map.get("buynumber"));
                jsonArray.add(jsonObject);

        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //根据id查询商品详情
    @Transactional
    public Object selectMillAllById(Integer productId) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(productId);
        String coin = martianOrePoolMapper.selectGoodsType(productId);
        String money = "6.61";
        String exchange = exchangeRateUtils.exchange(coin);
        BigDecimal CNY = new BigDecimal(BigDecimalUtils.mul(exchange, money, 8));
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("image",map.get("image"));
            jsonObject.put("pool_rate",map.get("pool_rate"));
            jsonObject.put("mill_cost",map.get("mill_cost"));
            jsonObject.put("description",map.get("description"));
            jsonObject.put("hashrate",map.get("hashrate"));
            jsonObject.put("administrative_fee",map.get("administrative_fee"));
            jsonObject.put("name",map.get("name"));
            jsonObject.put("stock",map.get("stock"));
            jsonObject.put("electric_charge",map.get("electric_charge"));
            jsonObject.put("power_diss",map.get("power_diss"));
            jsonObject.put("typename",map.get("type_name"));
            jsonObject.put("activity_price",map.get("activity_price"));
            jsonObject.put("cmc_subarea",map.get("cmc_subarea"));
            if (coin.equals("BTC")){
                Object btcEarningsByDay = web3JConfig.getBtcEarningsByDay(coin);
                //每TH/S  * 算力T = 币种单日收益
                BigDecimal multiplyHashrateBtc = new BigDecimal(btcEarningsByDay.toString()).
                        multiply(new BigDecimal(map.get("hashrate").toString()));
                //算力 * 币价 = 收益  日收益
                BigDecimal dailyEarnings = multiplyHashrateBtc.multiply(CNY);
                BigDecimal BackToDay = new BigDecimal(map.get("mill_cost").toString()).
                        divide(dailyEarnings,0,BigDecimal.ROUND_HALF_UP);
                jsonObject.put("Back_tothe",BackToDay);//计算得出
                jsonObject.put("earnings",multiplyHashrateBtc);
            }
            if (coin.equals("ETH")){
                Object ethEarningsByDay = getEthEarningsByDay(coin);
                //每TH/S  * 算力T = 币种单日收益/T
                BigDecimal multiplyHashrateEth = new BigDecimal(ethEarningsByDay.toString()).
                        multiply(new BigDecimal(map.get("hashrate").toString()));
                //算力 * 币价 = 收益  日收益
                BigDecimal dailyEarnings = multiplyHashrateEth.multiply(CNY);
                //回本周期
                BigDecimal Back_tothe = new BigDecimal(map.get("mill_cost").toString()).divide(dailyEarnings,0,BigDecimal.ROUND_HALF_UP);
                jsonObject.put("Back_tothe",Back_tothe);//计算得出
                jsonObject.put("earnings",multiplyHashrateEth);
            }
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(map.get("end_time").toString());
            String format = dateFormat.format(date);
            Date parse = dateFormat.parse(format);
            long parseTime = parse.getTime()/1000;
            jsonObject.put("parseTime",parseTime);
            jsonObject.put("mining_time",map.get("mining_time"));
            jsonObject.put("millCount",map.get("buynumber"));
            jsonArray.add(jsonObject);

        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }



    //云算力查询
    @Transactional
    public Object selectCloudHashrate(Integer goodsType,Integer typeMill) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectCloudHashrate(goodsType,typeMill);
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("productId",map.get("cmc_id"));
            jsonObject.put("cloud_hashrate",map.get("cloud_hashrate"));
            jsonObject.put("mining_time",map.get("mining_time"));
            jsonObject.put("unitprice",map.get("unit_tprice"));
            jsonObject.put("period",map.get("period"));
            jsonObject.put("titlte",map.get("titlte"));
            jsonObject.put("name",map.get("name"));
//            jsonObject.put("cloud_day",map.get("cloud_day"));
            jsonObject.put("electric_charge",map.get("electric_charge"));
            jsonObject.put("hashrate",map.get("hashrate"));
            jsonObject.put("power_diss",map.get("power_diss"));
            jsonObject.put("opera_cost",map.get("opera_cost"));
            jsonObject.put("static_return_days",map.get("static_return_days"));
            BigDecimal charge = new BigDecimal(map.get("power_diss").toString()).
                    multiply(new BigDecimal(map.get("electric_charge").toString()));
            BigDecimal chargeDay = charge.multiply(new BigDecimal(24));
            jsonObject.put("chargeDay",chargeDay);
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(map.get("mining_time").toString());
            String format = dateFormat.format(date);
            System.out.println(format);
            Date parse = dateFormat.parse(format);
            long parseTime = parse.getTime()/1000;
            jsonObject.put("parseTime",parseTime);
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //联合挖矿查询
    @Transactional
    public Object selectUnitedMining(Integer goodsType,Integer typeMill){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectUnitedMining(goodsType,typeMill);
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("productId",map.get("cmc_id"));
            jsonObject.put("hashrate",map.get("hashrate"));
            jsonObject.put("titlte",map.get("titlte"));
            jsonObject.put("name",map.get("name"));
            jsonObject.put("cloud_day",map.get("cloud_day"));
            jsonObject.put("mill_cost",map.get("mill_cost"));
            jsonObject.put("electric_charge",map.get("electric_charge"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //专区查询
    @Transactional
    public Object selectPrifecture(){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectPrifecture();
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("prefecture",map.get("prefecture"));
            jsonObject.put("prefectureId",map.get("prefectureId"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //矿种查询
    @Transactional
    public Object selectMinerals(){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMinerals();
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("minerals",map.get("minerals"));
            jsonObject.put("mineralsId",map.get("mineralsId"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //云算力订单页面
    @Transactional(rollbackFor = Exception.class)
    public Object hashrateOrderPage(Integer orderId,BigDecimal number){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(orderId);
        for (Map<String, Object> map : mapList){
            BigDecimal unitTprice = new BigDecimal(map.get("unit_tprice").toString()).multiply(number);
            BigDecimal administrative = new BigDecimal(map.get("administrative_fee").toString()).
                    multiply(unitTprice);
            BigDecimal bigDecimal = administrative.divide(new BigDecimal(100));
            jsonObject.put("price",unitTprice);
            jsonObject.put("administrative",bigDecimal);
            jsonObject.put("name",map.get("name"));
            jsonObject.put("unit_tprice",map.get("unit_tprice"));
            jsonObject.put("cloud_hashrate",map.get("cloud_hashrate"));
            jsonObject.put("period",map.get("period"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //矿机订单页面
    @Transactional(rollbackFor = Exception.class)
    public Object millOrderPage(Integer orderId,BigDecimal day,BigDecimal number){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(orderId);
        for (Map<String, Object> map : mapList){
            //今日电费计算
            BigDecimal electric = new BigDecimal(map.get("electric_charge").toString()).
                    multiply(new BigDecimal(map.get("power_diss").toString()));
            BigDecimal electricDay = electric.multiply(new BigDecimal(24));//电费
            //税费计算
            BigDecimal cose = new BigDecimal(map.get("tax_point").toString()).
                    multiply(new BigDecimal(map.get("mill_cost").toString())).multiply(number);
            //电费
            BigDecimal decimal = day.multiply(electricDay).multiply(number);
            //矿机总计
            BigDecimal mill_cost_sum = number.multiply(new BigDecimal(map.get("mill_cost").toString()));
            BigDecimal subtract = mill_cost_sum.subtract(cose);
            jsonObject.put("electricDay",electricDay);
            jsonObject.put("cose",cose);
            jsonObject.put("decimal",decimal);
            jsonObject.put("mill_cost_sum",subtract);
            jsonObject.put("electric_charge",map.get("electric_charge"));
            jsonObject.put("image",map.get("image"));
            jsonObject.put("name",map.get("name"));
            jsonObject.put("millNumber",map.get("buynumber"));
            jsonObject.put("carriage",map.get("carriage"));
            jsonObject.put("addressKey","0xfe8c35b58969ade2949be98ac9568ed8fae73545");
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    /**
     * @param type 1,usdt  2,银行卡
     **/
    //矿机订单支付
    @Transactional(rollbackFor = Exception.class)
    public Object payment(BigDecimal money, int type,Integer jypassword, String address, String addressKey,String toAddressKey,
                          Integer productId, Integer number, String backNumber, String backName, String name, MultipartFile file) {
        String uuid = Utils.getRandom(16);
        String logo = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = dateFormat.format(date);
        String exchange = "";
        Integer orderType = null;
        String product_name = "";
        BigDecimal decimal = null;
//        JSONObject jsonObject = exchangeRateUtils.exchangeRate(URL);
//        JSONObject object = jsonObject.getJSONArray("newslist").getJSONObject(0);
        Integer addressId = martianOrePoolMapper.selectIdByAddress(address);
        JSONArray jsonArray = new JSONArray();
        String coinMoney = custodyMapper.selectCoinMoneyByCoin(addressKey);
        Integer jYpassword = redPacketMapper.selectJYpassword(address);
        String moneyCny = "6.61";
        if (type == 1){
            if (money.compareTo(BigDecimal.ZERO) == -1) {
                return Utils.toJSON("非法数量", jsonArray.toString(), "1");
            }
            if (!jypassword.equals(jYpassword)) {
                return Utils.toJSON("交易密码错误，请重新输入", Utils.toJSONmap(), "3");
            }
            if (BigDecimalUtils.compare(money.toString(),coinMoney)){
                return Utils.toJSON("可用余额不足", Utils.toJSONmap(), "2");
            }
            //List<Map<String, Object>> mapList1 = martianOrePoolMapper.selectMillAllById(productId);
            //for (Map<String, Object> map : mapList1) {
            //decimal = new BigDecimal(map.get("mill_cost").toString()).multiply(new BigDecimal(number));
            //}
            //法币兑换成代币
            //BigDecimal decimalUsdt = decimal.divide(new BigDecimal(moneyCny), 7, BigDecimal.ROUND_HALF_UP);
//            try {
//                Custody.getCoinWithdraw("ETH-USDT",toAddressKey,money.toPlainString(), uuid);
//                boolean recordList = custodyUtils.getRecordList(uuid, address);
//                if (!recordList){
//                    return Utils.toJSON("交易失败，请联系客服",Utils.toJSONmap(),"4");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            try {
//                Custody.getCoinWithdraw("ETH_USDT",toAddressKey,decimalUsdt.toPlainString(), uuid);
//                boolean recordList = custodyUtils.getRecordList(uuid, address);
//                if (!recordList){
//                    return Utils.toJSON("交易失败，请联系客服",Utils.toJSONmap(),"4");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            //计算余额
            String subtractUsdt = new BigDecimal(coinMoney).subtract(money).toPlainString();
            //修改余额
            custodyMapper.updateCoinMoneyByAddressAndCoin(subtractUsdt,addressKey);
            List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(productId);
            redisUtils.setDataToCache(address+uuid,uuid);
            JSONObject jsonObject = null;
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                jsonObject.put("image",map.get("image"));
                jsonObject.put("name",map.get("name"));
                jsonObject.put("type_mill",map.get("type_mill"));
                jsonObject.put("millCount",map.get("buynumber"));
            }
            BigDecimal millCount = new BigDecimal(jsonObject.get("millCount").toString()).
                    subtract(new BigDecimal(number));
            logo = jsonObject.get("image").toString();
            product_name = jsonObject.getString("name");
            orderType = jsonObject.getInteger("type_mill");
            if (orderType == 3){
                orderType = 2;
            }
            Integer zt = 0;
            custodyUtils.addMillOrder(address,format,logo,money,zt,productId,number,type,uuid,orderType,product_name,addressId);
            martianOrePoolMapper.updateMillCount(millCount,productId);
            exchangeRateUtils.updateAward(money,addressId,number,type,address);
        }
        if (type == 2){
            List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(productId);
            JSONObject jsonObject = null;
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                jsonObject.put("image",map.get("image"));
                jsonObject.put("name",map.get("name"));
                jsonObject.put("type_mill",map.get("type_mill"));
                jsonObject.put("millCount",map.get("buynumber"));
            }
            String url = null;
            if (file == null || file.getSize() == 0) {
            } else {
                byte[] buffer = new byte[0];
                try {
                    buffer = file.getBytes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                url = fileUtil.saveFile("image", address, buffer);
            }
            logo = jsonObject.get("image").toString();
            product_name = jsonObject.getString("name");
            orderType = jsonObject.getInteger("type_mill");
            if (orderType == 3){
                orderType = 2;
            }
            YzcmInformation yzcmInformation = new YzcmInformation();
            yzcmInformation.setCmcAddress(address);
            yzcmInformation.setCmcBankName(backName);
            yzcmInformation.setCmcBankNumber(backNumber);
            yzcmInformation.setCmcImage(url);
            yzcmInformation.setCmcUsername(name);
            Integer zt = 1;
            BigDecimal millCount = new BigDecimal(jsonObject.get("millCount").toString()).
                    subtract(new BigDecimal(number));
            martianOrePoolMapper.insertInformation(yzcmInformation);
            custodyUtils.addMillOrder(address,format,logo,money,zt,productId,number,type,uuid,orderType,product_name,addressId);
            martianOrePoolMapper.updateMillCount(millCount,productId);
            BigDecimal divideMoney = money.divide(new BigDecimal(moneyCny), 6, BigDecimal.ROUND_HALF_UP);
            exchangeRateUtils.updateAward(divideMoney,addressId,number,type,address);
        }

        return Utils.toJSON("购买成功",jsonArray.toString(),"0");
    }

    /**
     * @param type 1,usdt  2,银行卡
     **/
    //云算力订单支付
    @Transactional(rollbackFor = Exception.class)
    public Object cloudPayment(BigDecimal money, int type, Integer jypassword, String address, String addressKey,String toAddressKey,
                          Integer productId, Integer number, String backNumber, String backName, String name, MultipartFile file) {
        String uuid = Utils.getRandom(16);
        String logo = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = dateFormat.format(date);
        String exchange = "";
        Integer orderType = null;
        String product_name = "";
        BigDecimal decimal = null;
//        JSONObject jsonObject = exchangeRateUtils.exchangeRate(URL);
//        JSONObject object = jsonObject.getJSONArray("newslist").getJSONObject(0);
        Integer addressId = martianOrePoolMapper.selectIdByAddress(address);
        JSONArray jsonArray = new JSONArray();
        String coinMoney = custodyMapper.selectCoinMoneyByCoin(addressKey);
        Integer jYpassword = redPacketMapper.selectJYpassword(address);
        String moneyCny = "6.61";
        if (type == 1){
            if (money.compareTo(BigDecimal.ZERO) == -1) {
                return Utils.toJSON("非法数量", jsonArray.toString(), "1");
            }
            if (!jypassword.equals(jYpassword)) {
                return Utils.toJSON("交易密码错误，请重新输入", Utils.toJSONmap(), "3");
            }
            if (BigDecimalUtils.compare(money.toString(),coinMoney)){
                return Utils.toJSON("可用余额不足", Utils.toJSONmap(), "2");
            }
            //法币兑换成代币
//            List<Map<String, Object>> mapList1 = martianOrePoolMapper.selectMillAllById(productId);
//            for (Map<String, Object> map : mapList1) {
//                decimal = new BigDecimal(map.get("mill_cost").toString()).multiply(new BigDecimal(number));
//            }
            //法币兑换成代币
//            BigDecimal decimalUsdt = decimal.divide(new BigDecimal(moneyCny), 7, BigDecimal.ROUND_HALF_UP);
            try {
                Custody.getCoinWithdraw("ETH-USDT",toAddressKey,money.toPlainString(), uuid);
                boolean recordList = custodyUtils.getRecordList(uuid, address);
                if (!recordList){
                    return Utils.toJSON("交易失败，请联系客服",Utils.toJSONmap(),"4");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //计算余额
            String subtractUsdt = new BigDecimal(coinMoney).subtract(money).toPlainString();
            //修改余额
            custodyMapper.updateCoinMoneyByAddressAndCoin(subtractUsdt,addressKey);
            List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(productId);
            redisUtils.setDataToCache(address+uuid,uuid);
            JSONObject jsonObject = null;
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                jsonObject.put("image",map.get("image"));
                jsonObject.put("name",map.get("name"));
                jsonObject.put("type_mill",map.get("type_mill"));
                jsonObject.put("cloud_hashrate",map.get("cloud_hashrate"));
            }
            BigDecimal millCount = new BigDecimal(jsonObject.get("cloud_hashrate").toString()).
                    subtract(new BigDecimal(number));
            logo = jsonObject.get("image").toString();
            product_name = jsonObject.getString("name");
            orderType = jsonObject.getInteger("type_mill");
            if (orderType == 3){
                orderType = 2;
            }
            Integer zt = 0;
            custodyUtils.addMillOrder(address,format,logo,money,zt,productId,number,type,uuid,orderType,product_name,addressId);
            martianOrePoolMapper.updateMillCount(millCount,productId);
            exchangeRateUtils.updateAward(money,addressId,number,type,address);
        }
        if (type == 2){
            List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAllById(productId);
            JSONObject jsonObject = null;
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                jsonObject.put("image",map.get("image"));
                jsonObject.put("name",map.get("name"));
                jsonObject.put("type_mill",map.get("type_mill"));
                jsonObject.put("cloud_hashrate",map.get("cloud_hashrate"));
            }
            String url = null;
            if (file == null || file.getSize() == 0) {
            } else {
                byte[] buffer = new byte[0];
                try {
                    buffer = file.getBytes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                url = fileUtil.saveFile("image", address, buffer);
            }
            logo = jsonObject.get("image").toString();
            product_name = jsonObject.getString("name");
            orderType = jsonObject.getInteger("type_mill");
            if (orderType == 3){
                orderType = 2;
            }
            YzcmInformation yzcmInformation = new YzcmInformation();
            yzcmInformation.setCmcAddress(address);
            yzcmInformation.setCmcBankName(backName);
            yzcmInformation.setCmcBankNumber(backNumber);
            yzcmInformation.setCmcImage(url);
            yzcmInformation.setCmcUsername(name);
            Integer zt = 1;
            System.out.println(jsonObject.get("cloud_hashrate"));
            BigDecimal millCount = new BigDecimal(jsonObject.get("cloud_hashrate").toString()).
                    subtract(new BigDecimal(number));
            martianOrePoolMapper.insertInformation(yzcmInformation);
            custodyUtils.addMillOrder(address,format,logo,money,zt,productId,number,type,uuid,orderType,product_name,addressId);
            martianOrePoolMapper.updateMillCount(millCount,productId);
            BigDecimal divideMoney = money.divide(new BigDecimal(moneyCny), 6, BigDecimal.ROUND_HALF_UP);
            exchangeRateUtils.updateAward(divideMoney,addressId,number,type,address);
        }
        return Utils.toJSON("购买成功",jsonArray.toString(),"0");
    }

    //以太坊区块奖励查询
    @Transactional(rollbackFor = Exception.class)
    public double getEthBlockNumberReward(){
        EthBlockNumber send = new EthBlockNumber();
        System.out.println(send);
        try {
            send = web3j.ethBlockNumber().send();
        } catch (IOException e) {
            LOG.warn("请求区块链信息异常 >> 区块数量,{}", e);
        }
        BigInteger blockNumber = send.getBlockNumber();
        String param = "blockno="+blockNumber+"&apikey="+APIKEY;
        JSONObject sendPost = GetAndPostParams.sendGet(ETHURL, param);
        JSONObject result = sendPost.getJSONObject("result");
        String blockReward = result.get("blockReward").toString();
        double mul = BigDecimalUtils.div(Double.parseDouble(blockReward), 1e18, 4);
        return mul;
    }

    //ETH收益计算
    public Object getEthEarningsByDay(String coin) throws ParseException {
        double ethBlockReward = getEthBlockNumberReward();
        BigDecimal bigDecimal = new BigDecimal(1000000).multiply(new BigDecimal(86400));
        BigDecimal decimal = bigDecimal.multiply(new BigDecimal(ethBlockReward));
        BigDecimal ethdifficulty = web3JConfig.getEthdifficulty(coin);
        String scale = decimal.divide(ethdifficulty,8,BigDecimal.ROUND_HALF_UP).toPlainString();
        return scale;
    }


    //BTC计算器
    @Transactional
    public Object calculator(String coin,BigDecimal price,BigDecimal number,BigDecimal hashrate,
                             BigDecimal energy,BigDecimal power,int type) throws ParseException {
        coin = coin.toUpperCase();
        Map<String,Object> objectMap = new HashMap<>();
        JSONArray jsonArray = new JSONArray();
        String money = "6.61";
        String exchange = new BigDecimal(exchangeRateUtils.exchange(coin)).multiply(new BigDecimal(0.954)).toString();
        BigDecimal CNY = new BigDecimal(BigDecimalUtils.mul(exchange, money, 8));
        Object btcEarningsByDay = web3JConfig.getBtcEarningsByDay(coin);
        //每TH/S  * 算力T = 币种单日收益
        BigDecimal multiplyHashrate = new BigDecimal(btcEarningsByDay.toString()).multiply(hashrate);
        //算力 * 币价 = 收益  日收益
        BigDecimal dailyEarnings = multiplyHashrate.multiply(CNY).multiply(number);
        //CNY日电费
        BigDecimal energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(24));
        //币种日电费
        BigDecimal energyChargeCoin =
                energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
        //CNY净收益
        BigDecimal subtractYield = dailyEarnings.subtract(energyCharge);
        //币种净收益
        BigDecimal subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);

        BigDecimal dayEarnigs = subtractYield;

        if (type == 1){

        } else if (type == 2){
            //月收益
            dailyEarnings = dailyEarnings.multiply(new BigDecimal(30)).multiply(number);
            //币种月收益
            multiplyHashrate = multiplyHashrate.multiply(number).multiply(new BigDecimal(30));
            //CNY月电费
            energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(30)).multiply(new BigDecimal(24));
            //币种月电费
            energyChargeCoin =  energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
            //CNY月净收益
            subtractYield = dailyEarnings.subtract(energyCharge);
            //币种月净收益
            subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);
        } else if (type == 3){
            //年收益
            dailyEarnings = dailyEarnings.multiply(new BigDecimal(365)).multiply(number);
            //币种年收益
            multiplyHashrate = multiplyHashrate.multiply(number).multiply(new BigDecimal(365));
            //CNY年电费
            energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(365)).multiply(new BigDecimal(24));
            //币种年电费
            energyChargeCoin =  energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
            //CNY年收益
            subtractYield = dailyEarnings.subtract(energyCharge);
            //币种年收益
            subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);
        }
        objectMap.put("dailyEarnings",dailyEarnings);//人民币收益
        objectMap.put("multiplyHashrate",multiplyHashrate);//币种收益
        objectMap.put("energyCharge",energyCharge);//电费
        objectMap.put("energyChargeCoin",energyChargeCoin);//币种电费
        objectMap.put("subtractYield",subtractYield);//人民币净收益；
        objectMap.put("subtractYieldCoin",subtractYieldCoin);//币种净收益
        objectMap.put("coinPrice",CNY);
        //回本周期
        BigDecimal BackToMoney = price.divide(dayEarnigs,0,BigDecimal.ROUND_HALF_UP);
        objectMap.put("BackToMoney",BackToMoney);
        jsonArray.add(objectMap);
        return Utils.toJSON("计算成功",jsonArray.toString(),"0");
    }

    //ETH计算器
    @Transactional
    public Object ethCalculator(String coin,BigDecimal price,BigDecimal number,BigDecimal hashrate,
                             BigDecimal energy,BigDecimal power,int type) throws ParseException {
        coin = coin.toUpperCase();
        Map<String,Object> objectMap = new HashMap<>();
        JSONArray jsonArray = new JSONArray();
        String money = "6.61";
        String exchange = new BigDecimal(exchangeRateUtils.exchange(coin)).multiply(new BigDecimal(0.946)).toString();
        BigDecimal CNY = new BigDecimal(BigDecimalUtils.mul(exchange, money, 8));
        Object ethEarningsByDay = getEthEarningsByDay(coin);
        //每TH/S  * 算力T = 币种单日收益
        BigDecimal multiplyHashrate = new BigDecimal(ethEarningsByDay.toString()).multiply(hashrate);
        //算力 * 币价 = 收益  日收益
        BigDecimal dailyEarnings = multiplyHashrate.multiply(CNY).multiply(number);
        System.out.println(dailyEarnings);
        //CNY日电费
        BigDecimal energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(24));
        //币种日电费
        BigDecimal energyChargeCoin =
                energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
        //CNY净收益
        BigDecimal subtractYield = dailyEarnings.subtract(energyCharge);
        //币种净收益
        BigDecimal subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);

        BigDecimal dayEarnigs = subtractYield;

        if (type == 1){

        } else if (type == 2){
            //月收益
            dailyEarnings = dailyEarnings.multiply(new BigDecimal(30)).multiply(number);
            //币种月收益
            multiplyHashrate = multiplyHashrate.multiply(number).multiply(new BigDecimal(30));
            //CNY月电费
            energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(30)).multiply(new BigDecimal(24));
            //币种月电费
            energyChargeCoin =  energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
            //CNY月净收益
            subtractYield = dailyEarnings.subtract(energyCharge);
            //币种月净收益
            subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);
        } else if (type == 3){
            //年收益
            dailyEarnings = dailyEarnings.multiply(new BigDecimal(365)).multiply(number);
            //币种年收益
            multiplyHashrate = multiplyHashrate.multiply(number).multiply(new BigDecimal(365));
            //CNY年电费
            energyCharge = power.multiply(energy).multiply(number).multiply(new BigDecimal(365)).multiply(new BigDecimal(24));
            //币种年电费
            energyChargeCoin =  energyCharge.divide(CNY, 7, BigDecimal.ROUND_HALF_UP).multiply(number);
            //CNY年收益
            subtractYield = dailyEarnings.subtract(energyCharge);
            //币种年收益
            subtractYieldCoin = multiplyHashrate.subtract(energyChargeCoin);
        }
        objectMap.put("dailyEarnings",dailyEarnings);//人民币收益
        objectMap.put("multiplyHashrate",multiplyHashrate);//币种收益
        objectMap.put("energyCharge",energyCharge);//电费
        objectMap.put("energyChargeCoin",energyChargeCoin);//币种电费
        objectMap.put("subtractYield",subtractYield);//人民币净收益；
        objectMap.put("subtractYieldCoin",subtractYieldCoin);//币种净收益
        objectMap.put("coinPrice",CNY);
        //回本周期
        BigDecimal BackToMoney = price.divide(dayEarnigs,0,BigDecimal.ROUND_HALF_UP);
        objectMap.put("BackToMoney",BackToMoney);
        jsonArray.add(objectMap);
        return Utils.toJSON("计算成功",jsonArray.toString(),"0");
    }

    //矿机配置
    @Transactional
    public Object selectMillConfig(Integer productId){
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillConfig(productId);
        for (Map<String, Object> map : mapList){
            jsonObject.put("dig_currency",map.get("dig_currency"));
            jsonObject.put("manufacturer",map.get("manufacturer"));
            jsonObject.put("algorithm",map.get("algorithm"));
            jsonObject.put("power_diss",map.get("power_diss"));
            jsonObject.put("dimensions",map.get("dimensions"));
            jsonObject.put("total_weight",map.get("total_weight"));
            jsonObject.put("refrigeration",map.get("refrigeration"));
            jsonObject.put("working_tempe",map.get("working_tempe"));
            jsonObject.put("power_conn_mode",map.get("power_conn_mode"));
            jsonObject.put("os_type",map.get("os_type"));
            jsonObject.put("video_memory",map.get("video_memory"));
            jsonObject.put("card_model",map.get("card_model"));
            jsonObject.put("calculate_rating",map.get("calculate_rating"));
            jsonObject.put("memory",map.get("memory"));
            jsonObject.put("description",map.get("description"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

}
